<?php

namespace App\Http\Controllers;

use App\Models\MyMessage;

use App\Models\RoadshowHistory;
use App\Http\Libs\Helper_Huanxin;
use App\Models\Maker;
use App\Models\User;
use App\Models\Project;
use App\Models\RoadShowApply;
use App\Models\RoadshowProject;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use \DB;
use App\Models\Notice;
use App\Http\Requests\RoadShowApplyRequest;

class RoadShowApplyController extends CommonController
{
    /**
     * 获取路演申请列表
     *
     * @return Response
     */
    public function getIndex()
    {
        $lists = DB::table('roadshow_apply')
            ->leftjoin('user', 'roadshow_apply.uid', '=', 'user.uid')
            ->leftjoin('maker', 'roadshow_apply.maker_id', '=', 'maker.id')
            ->select('roadshow_apply.*', 'user.nickname', 'user.realname', 'maker.name')
            ->orderBy('created_at', 'desc')
            ->paginate(10);

        return view('roadshowapply.index')->with('lists', $lists)->with("actions", $this->actions);
    }

    /**
     * @param Request $request
     * 执行一个搜索
     */
    public function search(Request $request)
    {
        $data = $request->input();
        $lists = RoadshowApply::with('user', 'maker');

        if (isset($data['makername']) && $data['makername'] != '') {
            $makerIds = Maker::where('name', 'like', '%'.trim($data['makername']).'%')->lists('id');
            $lists->whereIn('maker_id', $makerIds);
        }

        if (isset($data['username']) && $data['username'] != '') {
            $userIds = User::where('username', 'like', '%'.trim($data['username']).'%')->lists('uid');
            $lists->whereIn('uid', $userIds);

        }

        if (isset($data['initiator']) && $data['initiator'] != '') {
            $lists->where('initiator', $data['initiator']);
        }

        $lists = $lists->orderBy('created_at', 'desc')
            ->paginate(10);

        return view('roadshowapply.search')->with("lists", $lists)->with("username", trim($data['username']))
            ->with("makername", trim($data['makername']))->with("initiator", $data['initiator'])->with("actions", $this->actions);
    }

    /**
     * 获取与该路演申请相关联的项目列表
     *
     */
    public function getProject(Request $request)
    {
        $data = $request->input();
        $lists = RoadshowProject::with('project')->where('roadshow_apply_id', $data['id'])->paginate(10);

        return view('roadshowapply.project')->with('lists', $lists);
    }

    /**
     * 获取编辑页面
     *
     */
    public function getEdit(Request $request)
    {
        $id = $request->input('id');
        $list = DB::table('roadshow_apply')
            ->leftjoin('user', 'roadshow_apply.uid', '=', 'user.uid')
            ->leftjoin('maker', 'roadshow_apply.maker_id', '=', 'maker.id')
            ->select('roadshow_apply.*', 'user.nickname', 'maker.name')
            ->where('roadshow_apply.id', '=', $id)
            ->first();

        return view('roadshowapply.edit')->with('list', $list);
    }

    /**
     * 审核一个路演申请
     *
     */
    public function postEdit(RoadShowApplyRequest $request)
    {
        $data = $request->input();
        if(-1==$data['status']){
            DB::table('roadshow_apply')
                ->where('id', '=', $data['id'])
                ->update(['status' => $data['status'], 'reason' => $data['reason']]);
        }else{
            DB::table('roadshow_apply')
                ->where('id', '=', $data['id'])
                ->update(['status' => $data['status'], 'reason' => '']);
        }


        $lists = RoadshowProject::with('project')->where('roadshow_apply_id', $data['id'])->get();
        $is_roadshow = $data['status'] == 1 ? 1 : 0;

        if (!empty($lists)) {
            foreach ($lists as $v) {
                Project::where('id', $v->project_id)->update(['is_roadshow' => $is_roadshow]);
                1 == $data['status'] && Notice::create(['title' => '您的项目已通过审核，应邀参加无界路演', 'content' => trans('webNotice.projectSuccess.content', ['project' => $v->project->subject]), 'type' => 1, 'uid' => $v->project->uid]);
                $roadshowApply=RoadShowApply::where('id',$v->roadshow_apply_id)->first();
                if(isset($roadshowApply->id)){
                	RoadshowHistory::create(array('project_id'=>$v->project_id,'uid'=>$roadshowApply->uid,'maker_id'=>$roadshowApply->maker_id,'status'=> $data['status'],'initiator'=>$roadshowApply->initiator,'reason'=>$roadshowApply->reason));
                }
                $user=User::where('uid',$roadshowApply->uid)->first();
                $project_id=$v->project_id;
                $project=Project::where('id',$project_id)->first();
                if($data['status']==1){
                	//路演申请通过
                	if(isset($roadshowApply->id)){
                		$iosUsers=User::where('status',1)->where('client_type','ios')->where('token','<>','')->where('is_huanxin',1)->where('uid',$roadshowApply->uid)->get();
                		$androidUsers=User::where('status',1)->where('client_type','android')->where('client_id','<>','')->where('is_huanxin',1)->where('uid',$roadshowApply->uid)->get();
						$url=$this->_appurl."/roadshow/projectstatus?pagetag=02-72-3";
                		if($roadshowApply->initiator=="project"){
                			//项目方
                			$content_gt=trans('gt.roadshowShenheSuccessProject');
                			$content_sms=trans('sms.roadshowShenheSuccessProject');
                			$content_app=trans('app.roadshowShenheSuccessProject');
                			@SendSMS($user->username,$content_sms,'roadshowShenheSuccessProject');
//                			@Helper_Huanxin::sendMessage(array($user->uid), $content_app,$from="admin",$ext=array(
//    							'type'=>"hyperjump",
//								'content'=>array(array('hyper'=>'点击了解详情','text'=>$url))
//    						));
                			@pushMessageToClient($iosUsers,$androidUsers,'无界投融',
                				$content_gt,
                				json_encode(array('type'=>'url','url'=>$url)));
                		}else{
                			//创客
                			$content_gt=trans('gt.roadshowShenheSuccessMaker');
                			$content_sms=trans('sms.roadshowShenheSuccessMaker');
                			$content_app=trans('app.roadshowShenheSuccessMaker');
                			@SendSMS($user->username,$content_sms,'roadshowShenheSuccessMaker');
//                			@Helper_Huanxin::sendMessage(array($user->uid), $content_app,$from="admin",$ext=array(
//    								'type'=>"hyperjump",
//									'content'=>array(array('hyper'=>'点击了解详情','text'=>$url))
//    						));
                			@pushMessageToClient($iosUsers,$androidUsers,'无界投融',
                				$content_gt,
                				json_encode(array('type'=>'url','url'=>$url)));
                		}
                	}
                }else{
                	//失败

                	$reason=$roadshowApply->reason?$roadshowApply->reason:'项目不符合近期近几期无界路演所规定的路演标准';
                	$url=$this->_appurl."/roadshow/history?pagetag=02-72-4";
                    $content_sms=trans('sms.roadshowShenheFailureProject');
                	if($roadshowApply->initiator=="project"){
                		//项目方
                		$content_app=trans('app.roadshowShenheFailureProject',array('subject'=>$project->subject,'reason'=>$reason));
                	}else{
                		//创客
                		$content_app=trans('app.roadshowShenheFailureMaker',array('subject'=>$project->subject,'reason'=>$reason));
                	}
                    @SendSMS($user->username,$content_sms,'roadshowShenheFailureProject');
                    $m_title='很抱歉您申请的我要路演没有成功';
                    $m_content='你于'.date('Y年m月d日',strtotime($roadshowApply->created_at)).'申请的“我要路演”没有成功选入近期的无界路演。';
                    $m_ext='<div class="mt10 mb10 dark2_gray">
                                <p>路演项目：<span class="orange">'.$project->subject.'</span></p>
                                <p>拒绝理由：<span class="lightgray2">'.$reason.'</span></p>
	                            </div>
	                            <div class="borderLine"></div>';
                    $m_end='<p>如有疑问咨询，或对结果有质疑，请联系客服<span class="orange">400-033-0176</span></p>';
                    MyMessage::createMessage($user->uid,$m_title,'official',$m_content,$m_ext,$m_end);
                	
                }
            }
        }

            return AjaxCallbackMessage('审核成功', true, url('roadshowapply/index'));

    }
}
